

package pers.ljf.escloud.controller.app.shiro;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import pers.ljf.escloud.dao.entity.app.User;
import pers.ljf.escloud.dao.entity.app.UserToken;
import pers.ljf.escloud.service.modules.app.UserService;
import pers.ljf.escloud.service.modules.sys.SysUserService;
import pers.ljf.escloud.service.modules.sys.SysUserTokenService;

import javax.annotation.Resource;

/**
 * 认证
 *
 * @author Mark sunlightcs@gmail.com
 */
//@Component
public class AppOAuth2Realm extends AuthorizingRealm {

    @Resource
    private UserService userService;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof AppOAuth2Token;
    }

    /**
     * 授权(验证权限时调用)
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return new SimpleAuthorizationInfo();
    }

    /**
     * 认证
     * 登录时token在mysql刷新（不存在则新建）
     * 非登陆的需要auth的调用都会调用本方法取request中的token校验
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String accessToken = (String) token.getPrincipal();

        User user = userService.validateUserToken(accessToken);

        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, accessToken, getName());
        return info;
    }
}
